package com.hamster.crm.service.impl;

import com.hamster.crm.mapper.PermissionMapper;
import com.hamster.crm.mapper.RoleAndPermissionMapper;
import com.hamster.crm.pojo.dto.PermissionGroupDTO;
import com.hamster.crm.pojo.dto.RoleAndPermission;
import com.hamster.crm.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 权限管理的 Service
 * @author Tarry
 * @create 2020/1/8 11:59
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleAndPermissionMapper roleAndPermissionMapper;

    /**
     * 分组查询权限列表
     * @return
     */
    @Override
    public List<PermissionGroupDTO> listPermissions() {
       return permissionMapper.listPermissions();
    }

    /**
     *  * 保存权限
     * @param ids 所选的权限id集合
     * @param roleId 角色的id
     */
    @Override
    @Transactional
    public void savePermission(String roleId,List<String> ids) {
        //先删除，在添加
        roleAndPermissionMapper.deleteByRoleId(roleId);//删除

        for (String id : ids) {
            RoleAndPermission roleAndPermission = new RoleAndPermission();
            roleAndPermission.setRoleId(roleId);
            roleAndPermission.setPermissionId(id);
            roleAndPermissionMapper.insert(roleAndPermission);
        }

    }

    /**
     * 根据角色id，查询该角色拥有的权限 id集合
     * @param roleId
     * @return
     */
    @Override
    public List<String> getPermissionByRoleId(String roleId) {
       return roleAndPermissionMapper.getPermissionByRoleId(roleId);
    }


}
